using System;
using System.Collections.Generic;
using System.Text;
using SlimDX.Direct3D9;
using SlimDX;
using Barrage.Global;

namespace Barrage.Render.Passes
{
    /// <summary>
    /// Extension to RenderPass that creates an antialiased render target
    /// </summary>
    public class AntialiasRenderPass : RenderPass
    {
        private Surface renderSurface;

        /// <summary>
        /// \internal Returns the render target associated with this pass
        /// </summary>
        public override SlimDX.Direct3D9.Surface RenderTargetSurface
        {
            get
            {
                return renderSurface;
            }
        }

        /// <summary>
        /// Inits the render pass with default window size
        /// </summary>
        public AntialiasRenderPass()
            : this(new Vector2(Engine.DefaultRenderTargetDescription.Width, Engine.DefaultRenderTargetDescription.Height))
        {
        }

        /// <summary>
        /// Inits the render pass with a specified size
        /// </summary>
        /// <param name="size">Render target size</param>
        public AntialiasRenderPass(Vector2 size)
            : base(false)
        {
            // Esta textura no es exactamente un RT
            RenderTarget = new Texture(Engine.Device, (int)size.X, (int)size.Y, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default);
            // Dado que vamos a hacer antialiasing, necesitamos un depth buffer con antialiasing
            DepthBuffer = Surface.CreateDepthStencil(Engine.Device, (int)size.X, (int)size.Y, Format.D24S8, MultisampleType.NonMaskable, 0, true);
            this.renderSurface = Surface.CreateRenderTarget(Engine.Device, (int)size.X, (int)size.Y, Format.X8R8G8B8, MultisampleType.NonMaskable, 0, false);
            TargetOwner = true;
            DepthBufferOwner = true;
        }

        /// <summary>
        /// \internal Ends the render to this render target
        /// </summary>
        public override void End()
        {
            base.End();
            Engine.Device.StretchRectangle(renderSurface, renderTargetSurface, TextureFilter.Point);
        }

        /// <summary>
        /// \internal Clear resources
        /// </summary>
        public override void Dispose()
        {
            renderSurface.Dispose();
            renderSurface = null;
            base.Dispose();
        }
    }
}
